package com.ts.controller.common;

import com.ts.result.Result;
import com.ts.utils.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口，用于文件上传
 */
@RestController
@RequestMapping("/admin/common")
@Tag(name = "通用接口", description = "文件上传等通用功能")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @Operation(summary = "文件上传", description = "上传文件到阿里云OSS")
    @PostMapping("/upload")
    //返回值string是因为要返回文件网址
    //MultipartFile是mvc框架已经封装好的类，用来接收文件  参数名与前端保持一致
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀
            String extension =
                    originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //调用工具类上传文件，参数为文件的字节数组+名称，名称这里使用uuid+文件后缀的形式
            //接收文件访问网址
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e);
        }
        return Result.error("文件上传失败");
    }
}
